﻿#region  Copyright (C) 2012 Unisys Corporation

// =============================================================================================
// All Rights Reserved. This work contains trade secrets and confidential material of UNISYS, 
// and its use or disclosure in whole or in part without explicit written permission of 
// UNISYS is prohibited. 
//  
// Product Name          :  Unisys e-Workflow and Imaging
// File Name             :  ConfigAdministrator.cs
// Authored By           :  Unisys Corporation
// Description           :	Object that all methods for read the files of images.
// =============================================================================================
//	Modified by                         Date            Version
// =============================================================================================
//	carlos.solis@cr.unisys.com      Feb 13, 2013    Initial Version
//  ronald.aguilar@cr.unisys.com         -          Initial Version
// =============================================================================================

#endregion

#region Using Region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using UnisysMassiveImporter_v2.Entidades.Configuracion;
using UnisysMassiveImporter_v2.Entidades.Mensajes;
using UnisysMassiveImporter_v2.Negocio.InfoImage;
using UnisysMassiveImporter_v2.Datos.Archivos;
#endregion

namespace UnisysMassiveImporter_v2.Negocio.Administrators
{
    public class ConfigAdminitrator
    {
        public InfoMessage infoMessage=new InfoMessage();       
        
        public bool CheckAppConfig(ref Configuration appConfig)
        {
          
            try
            {
                if (appConfig.system.Equals(""))
                    return false;

                

                if (!(CheckLogs(ref appConfig)))
                    return false;

                infoMessage = new InfoMessage();
                infoMessage.sendMessage("Verificando configuracion de la aplicacion....", InfoMessage.Information_Message, 501, "System", ref appConfig);

                if (!(CheckErrorDirectory(ref appConfig)))
                    return false;

                if (!(CheckHistory(ref appConfig)))
                    return false;

                if (!(CheckThreadSection(ref appConfig)))
                    return false;

                return true;
            }
            catch (Exception exc)
            {
                return false;
            }

        } //end VerificarAppConfig()

        private bool CheckLogs(ref Configuration appConfig)
        {
            try
            {
              
               // infoMessage.sendMessage("Verificando Seccion de Logs...",InfoMessage.Information_Message, 502,"System");
                String registro = "HKEY_LOCAL_MACHINE\\Software\\Unisys\\Unisys Massive Importer";
               // infoMessage.sendMessage("Intentando leer la direccion del registro: " + registro, InfoMessage.Information_Message, 503, "System");

                bool _fileSystem = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "FileSystemLog", false).ToString());
                //infoMessage.sendMessage("Llave FileSystemLog cargada con exito, valor actual: " + _fileSystem.ToString(), InfoMessage.Success_Message, 252, "System");                


                bool Configuration_Error = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "Configuration_Error", false).ToString());
                bool DB_Error = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "DB_Error", false).ToString());
                bool IIF_Error = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "IIF_Error", false).ToString());
                bool Information_Message = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "Information_Message", false).ToString());
                bool IO_Error = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "IO_Error", false).ToString());
                bool Success_Message = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "Success_Message", false).ToString());
                bool System_Error = Boolean.Parse(Microsoft.Win32.Registry.GetValue(registro, "System_Error", false).ToString());

                //infoMessage.sendMessage("Llave LevelLoger cargada con exito, valor actual: " + _levelLog.ToString(), InfoMessage.Success_Message, 253, "System");


                if (_fileSystem)
                {
                    System.IO.DirectoryInfo log = new System.IO.DirectoryInfo(appConfig.logLocation);
                    if (!(log.Exists))
                    {
                        try
                        {
                            log.Create();
                            //infoMessage.sendMessage("El directorio de logs " + log.FullName + " fue creado con exito", InfoMessage.Success_Message, 254, "System");
                        }
                        catch (Exception e)
                        {
                            //CriticalMessage criticalMessage = new CriticalMessage(appConfig);
                            //criticalMessage.sendMessage("El directorio " + log.FullName + " no existe y no pudo ser creado ", e, CriticalMessage.Configuration_Error, 52, "System", false);
                            Logger.LogThis4Windows("Error al verificar la seccion de logs " + e.Message, "Unisys Masive Importer", "Unisys Masive Service");
                            return false;
                        }
                    }
                    else
                    {
                        //infoMessage.sendMessage("Directorio de logs: " + log.FullName + " localizado con exito", InfoMessage.Success_Message, 255, "System");
                     
                    }
                }

                
                //verificar q el logSize sea mayor a 0

                if (appConfig.logSize <= 0)
                {
                    Logger.LogThis4Windows("Error al verificar la seccion de logs el logSize es menor que 1", "Unisys Masive Importer", "Unisys Masive Service");
                    return false;
                }
                infoMessage.sendMessage("Seccion de Logs ok", InfoMessage.Information_Message, 406, "System",ref  appConfig);

                return true;

            }
            catch (Exception e)
            {
                Logger.LogThis4Windows("Error al verificar la seccion de logs " + e.Message, "Unisys Masive Importer", "Unisys Masive Service");
                return false;
            }

     
           
        } //end CheckLogs()

        private bool CheckErrorDirectory(ref Configuration appConfig)
        {
            
            try
            {
                infoMessage.sendMessage("Verificando Seccion de Control de Errores", InfoMessage.Information_Message, 507, "System", ref appConfig);
                System.IO.DirectoryInfo errorDir = new System.IO.DirectoryInfo(appConfig.fileSystemError);
                if (!(errorDir.Exists))
                {
                    try
                    {
                        errorDir.Create();
                        infoMessage.sendMessage("El directorio de errores " + errorDir.FullName + " fue creado con exito", InfoMessage.Success_Message, 254, "System", ref appConfig);
                    }
                    catch (Exception e)
                    {
                        CriticalMessage criticalMessage = new CriticalMessage();
                        criticalMessage.sendMessage("El directorio " + errorDir.FullName + " no existe y no pudo ser creado ", e, CriticalMessage.Configuration_Error, 52, "System", false, ref appConfig);
                        return false;
                    }
                }
                else
                {

                    infoMessage.sendMessage("Directorio de  logs: " + errorDir.FullName + " localizado con exito", InfoMessage.Success_Message, 255, "System", ref appConfig);
                }
                infoMessage.sendMessage("Seccion de Control de Errores ok", InfoMessage.Information_Message, 508, "System", ref appConfig);
                return true;
            }
            catch (Exception exc)
            {
                return false;
 
            }
            
        }//end CheckErrorDirectory()

        private bool CheckHistory(ref Configuration appConfig)
        {           
            
            infoMessage.sendMessage("Verificando Seccion de Control de Historial",InfoMessage.Information_Message,509, "System", ref appConfig);
            try
            {
                if (appConfig.historyGeneration)
                {
                    System.IO.DirectoryInfo history = new System.IO.DirectoryInfo(appConfig.fileSystemHistory);
                    if (!(history.Exists))
                    {
                        try
                        {
                            history.Create();
                            infoMessage.sendMessage("El directorio de History " + history.FullName + " fue creado con exito.", InfoMessage.Success_Message, 254, "System", ref appConfig);
                            return true;
                        }
                        catch (Exception e)
                        {
                            CriticalMessage criticalMessage = new CriticalMessage();
                            criticalMessage.sendMessage("Error: el directorio " + history.FullName + " no existe y no pudo ser creado.", e, CriticalMessage.Configuration_Error, 52, "System", false, ref appConfig);
                            return false;
                        }
                    }
                    else
                    {
                        infoMessage.sendMessage("Directorio de History: " + history.FullName + " localizado con exito.", InfoMessage.Success_Message, 255, "System", ref appConfig);
                        return true;
                    }

                    infoMessage.sendMessage("Seccion de Control de Historial ok.", InfoMessage.Information_Message, 510, "System", ref appConfig);
                    //return true;
                }

                return true;
            }
            catch (Exception exc)
            {
                return false;
            }

        }//end CheckHistory()

        private bool CheckThreadSection(ref Configuration appConfig) 
        {
            try
            {
                infoMessage.sendMessage("Verificando Seccion de Configuracion de Threads", InfoMessage.Information_Message, 511, "System", ref appConfig);

                System.IO.DirectoryInfo configThreads = new System.IO.DirectoryInfo(appConfig.config_threadLocation);
                if (!(configThreads.Exists))
                {
                    CriticalMessage criticalMessage = new CriticalMessage();
                    criticalMessage.sendMessage("La Configuracion de los Threads no se encuentra disponible  o es inexistente", new Exception("No se encontro la carpeta: " + configThreads.FullName), CriticalMessage.Configuration_Error, 54, "System", false, ref appConfig);
                    return false;
                }
                else
                {
                    infoMessage.sendMessage("Directorio de configuracion: " + configThreads.FullName + " localizado con exito", InfoMessage.Success_Message, 255, "System", ref appConfig);
                }

                infoMessage.sendMessage("Seccion de Configuracion de Threads ok", InfoMessage.Information_Message, 512, "System", ref appConfig);
                return true;
            }
            catch (Exception exc)
            {
                return false;
            }

        }

        public bool CheckThreadConfig(Thread_Config threadConfig, ref Configuration appConfig) 
        {
            try
            {
                if(!threadConfig.Name.Equals(""))
                {
                    infoMessage.sendMessage("Verificando configuracion del thread [" + threadConfig.Name + "].",InfoMessage.Information_Message,518,threadConfig.Name,ref appConfig);

                    if (!(CheckIIFConnection(threadConfig, ref appConfig)))
                        return false;

                        #region Check Files Configuration

                    infoMessage.sendMessage("Verificando Seccion de Archivos Data", InfoMessage.Information_Message, 522, threadConfig.Name, ref appConfig);
                        System.IO.DirectoryInfo data = new System.IO.DirectoryInfo(threadConfig.DataPath);
                        if (data.Exists)
                        {
                            infoMessage.sendMessage("Directorio de data: " + data.FullName + " localizado con exito", InfoMessage.Success_Message, 255, threadConfig.Name, ref appConfig);
                            switch (threadConfig.DirectoryOrganization)
                            {
                                case 1:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + data.FullName + " la carpeta Data", InfoMessage.Information_Message, 523, threadConfig.Name, ref appConfig);
                                    } break;
                                case 2:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + data.FullName + " la data", InfoMessage.Information_Message, 523, threadConfig.Name, ref appConfig);
                                    } break;
                                case 3:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + data.FullName + " los subdirectorios de los documentos para encontrar la data correspondiente", InfoMessage.Information_Message, 523, "System", ref appConfig);
                                    } break;
                                default:
                                    {
                                        CriticalMessage cMessage=new CriticalMessage("Parametro de DirectoryOrganization no esta bien configurado Thread: " + threadConfig.Name + ". Valor Actual: " + threadConfig.DirectoryOrganization.ToString(), new Exception("Valor DirectoryOrganization Invalido"), CriticalMessage.Configuration_Error, 59,"System",false);
                                        cMessage.sendMessage(ref appConfig);
                                        return false;
                                    }
                            }
                        }
                        else
                        {
                            CriticalMessage criticalMessage = new CriticalMessage();
                            criticalMessage.sendMessage("Directorio de data: " + data.FullName + " no fue localizado con exito", new Exception("La carpeta " + data.FullName + " no exite"), CriticalMessage.Configuration_Error, 52, threadConfig.Name, false, ref appConfig);
                            return false;
                        }
                        infoMessage.sendMessage("Seccion de Archivos Data ok", InfoMessage.Information_Message, 525, threadConfig.Name, ref appConfig);


                        infoMessage.sendMessage("Verificando Seccion de Archivos Images", InfoMessage.Information_Message, 526, threadConfig.Name, ref appConfig);
                        System.IO.DirectoryInfo images = new System.IO.DirectoryInfo(threadConfig.ImagesPath);
                        if (images.Exists)
                        {
                            infoMessage.sendMessage("Directorio de imagenes: " + images.FullName + " localizado con exito", InfoMessage.Success_Message, 255, threadConfig.Name, ref appConfig);
                            switch (threadConfig.DirectoryOrganization)
                            {
                                case 1:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + images.FullName + " la carpeta Images", InfoMessage.Information_Message, 524, threadConfig.Name, ref appConfig);
                                    } break;
                                case 2:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + data.FullName + " las imagenes", InfoMessage.Information_Message, 524, threadConfig.Name, ref appConfig);
                                    } break;
                                case 3:
                                    {
                                        infoMessage.sendMessage("El thread buscara dentro de los subdirectorios de " + data.FullName + " los subdirectorios de los documentos para encontrar las imagenes correspondiente", InfoMessage.Information_Message, 524, "System", ref appConfig);
                                    } break;
                                default:
                                    {
                                        CriticalMessage criticalMessage = new CriticalMessage();
                                        criticalMessage.sendMessage("Parametro de DirectoryOrganization no esta bien configurado Thread: " + threadConfig.Name + ". Valor Actual: " + threadConfig.DirectoryOrganization.ToString(), new Exception("Valor DirectoryOrganization Invalido"), CriticalMessage.Configuration_Error, 59, threadConfig.Name, false, ref appConfig);
                                        return false;
                                    }
                            }
                        }
                        else
                        {
                            CriticalMessage criticalMessage = new CriticalMessage();
                            criticalMessage.sendMessage("Directorio de imagenes: " + images.FullName + " no fue localizado con exito", new Exception("La carpeta " + data.FullName + " no exite"), CriticalMessage.Configuration_Error, 52, threadConfig.Name, false, ref appConfig);
                            return false;
                        }
                        infoMessage.sendMessage("Seccion de Archivos Images ok", InfoMessage.Information_Message, 628, threadConfig.Name, ref appConfig);
                        #endregion

                        #region Check File Type

                        infoMessage.sendMessage("Verificando Seccion de FileType", InfoMessage.Information_Message, 527, "System", ref appConfig);
                        switch (threadConfig.Filetype)
                        {
                            case 1:
                                {
                                    infoMessage.sendMessage("El thread buscara archivos XML como archivos data y archivos TIF, TIFF o PDF para las imagenes", InfoMessage.Information_Message, 528, threadConfig.Name, ref appConfig);
                                } break;
                            case 2:
                                {
                                    infoMessage.sendMessage("El thread buscara archivos CSV como archivos data y archivos TIF, TIFF o PDF para las imagenes", InfoMessage.Information_Message, 528, threadConfig.Name, ref appConfig);
                                } break;
                            case 3:
                                {
                                    infoMessage.sendMessage("El thread buscara archivos DDF como archivos data y archivos TIF, TIFF o PDF para las imagenes", InfoMessage.Information_Message, 528, threadConfig.Name, ref appConfig);
                                } break;
                            default:
                                {
                                    CriticalMessage criticalMessage = new CriticalMessage();
                                    criticalMessage.sendMessage("Parametro de FileType no esta bien configurado Thread: " + threadConfig.Name + ". Valor Actual: " + threadConfig.Filetype, new Exception("Valor FileType Invalido"), CriticalMessage.Configuration_Error, 60, threadConfig.Name, false, ref appConfig);
                                    return false;
                                }
                        }

                        infoMessage.sendMessage("Seccion de FileType ok", InfoMessage.Information_Message, 529, threadConfig.Name, ref appConfig);

                        #endregion

                        if (threadConfig.MaxFiles < 1)
                            return false;

                        if (!(System.IO.File.Exists(threadConfig.required_fields)))
                            return false;


                        #region Check Delay

                        if (threadConfig.Delay <= 0)
                        {
                            infoMessage.sendMessage("La configuracion del Thread: " + threadConfig.Name + " esta correcta.", InfoMessage.Success_Message, 262, threadConfig.Name, ref appConfig);
                            return false;                            
                        }

                        #endregion

                        return true;               
                }
                else
                {
                    CriticalMessage criticalMessage = new CriticalMessage();
                    criticalMessage.sendMessage("EL nombre del thread no puede estar en blanco", new Exception("Campo Name del Thread esta en blanco"), CriticalMessage.Configuration_Error, 56, threadConfig.Name, false, ref appConfig);
                
                    return false;
                }
               
            }
            catch (Exception exc) 
            {
                return false;
            }
        } //end CheckThreadConfig

        private bool CheckIIFConnection(Thread_Config threadConfig,ref Configuration appConfig)
        {
            try
            {

                infoMessage.sendMessage("Verificando Sección de IIF.", InfoMessage.Information_Message, 519, threadConfig.Name, ref appConfig);
                IIF_Connection infoImage = new IIF_Connection();

                if (infoImage.CreateIIFClient(threadConfig.IIFUser, threadConfig.IIFPassword, threadConfig.IIFDomain, ref appConfig,ref threadConfig))
                {
                    infoMessage.sendMessage("Conexion con IIF establecida: usuario " + threadConfig.IIFUser + " conectado con exito", InfoMessage.Success_Message, 260, threadConfig.Name, ref appConfig);

                    infoImage.DestroyIIFClientExplicit();
                    infoMessage.sendMessage("Desconexion con IIF realizada con exito", InfoMessage.Success_Message, 261, threadConfig.Name, ref appConfig);

                }
                else
                {
                    CriticalMessage criticalMessage = new CriticalMessage();
                    criticalMessage.sendMessage("No se pudo realizar la conexion con IIF: usuario " + threadConfig.IIFUser + " no conectado, revisar log.", new Exception("Error Inesperado"), CriticalMessage.Configuration_Error, 57, threadConfig.Name, false, ref appConfig);
                    return false;
                }
                infoMessage.sendMessage("Seccion de IIF ok", InfoMessage.Information_Message, 521, threadConfig.Name, ref appConfig);	

                return true;
            }
            catch(Exception exc)
            {
                return false;
            }
        }//end CheckIIFConnection()
        
    }
}
